package com.springboot.service.impl;

import com.springboot.enums.ExchangeEnum;
import com.springboot.enums.QueueEnum;
import com.springboot.service.QueueMessageService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class QueueMessageServiceImpl implements QueueMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void send(Object message, ExchangeEnum exchange, QueueEnum queue) {

        //设置回调为当前类对象
        rabbitTemplate.setConfirmCallback(this);

        //构建回调id为uuid
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend(exchange.getValue(), queue.getRoutingKey(), message, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        System.out.println(" 回调id:" + correlationData.getId());
        if (b) {
            System.out.println("消息发送成功");
        } else {
            System.out.println("消息发送失败:" + s);
        }
    }
}
